#include "glew/glew.h"
#include "soil/SOIL.h"

#include "Texture.hpp"
#include "TextureDictionary.hpp"

namespace fge
{

Texture::Texture()
	: textureId(0), filterType(TextureFilter::Linear)
{
}

Texture::~Texture()
{
	if(textureId != 0)
		glDeleteTextures(1, &textureId);
}

void Texture::SetFilter(TextureFilter::Type filterType)
{
	glBindTexture(GL_TEXTURE_2D, textureId);

	switch(filterType)
	{
	default:
	case TextureFilter::Linear:
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		break;

	case TextureFilter::NearestNeighbor:
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
		break;
	}
}

Texture* Texture::FromFile(const std::string &fileName, TextureRegion *textureRegion)
{
	Texture *texture = new Texture();
	texture->textureId = SOIL_load_OGL_texture(fileName.c_str(), SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, 0, &texture->width, &texture->height);
	if(texture->textureId == 0)
	{
		delete texture;
		return NULL;
	}

	if(textureRegion != NULL)
	{
		textureRegion->rect.x = textureRegion->rect.y = 0;
		textureRegion->origin = fge::Vector2(0.5f, 0.5f);
		textureRegion->rect.w = texture->GetWidth();
		textureRegion->rect.h = texture->GetHeight();
	}

	return texture;
}

}

